package com.example.springbootdatamock.util;

import okhttp3.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class HttpUtil {
    static {
//         if (client == null)
        synchronized (com.example.springbootdatamock.util.HttpUtil.class) {
//             if (client == null)
            client = new OkHttpClient();
        }
    }

    private static OkHttpClient client;
    private String logUrl;

    public HttpUtil(String url) {
        this.logUrl = url;
    }


    public void get(String json, String name) {
        String encodeJson = "";
        try {
            encodeJson = URLEncoder.encode(json, "utf-8");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = this.logUrl + "?" + name + "=" + encodeJson;

        Request request = (new Request.Builder()).url(url).get().build();
        Call call = client.newCall(request);
        Response response = null;
        long start = System.currentTimeMillis();
        try {
            response = call.execute();
            long end = System.currentTimeMillis();
            System.out.println(response.body().string() + " used:" + (end - start) + " ms");

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("发送失败...检查网络地址...");
        }
    }


    public void post(String json) {
        System.out.println(json);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);


        Request request = (new Request.Builder()).url(this.logUrl).post(requestBody).build();
        Call call = client.newCall(request);
        Response response = null;
        long start = System.currentTimeMillis();
        try {
            response = call.execute();
            long end = System.currentTimeMillis();
            System.out.println(response.body().string() + " used:" + (end - start) + " ms");

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("发送失败...检查网络地址...");
        }
    }
}



 